package utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Saver {
	public boolean save(String ip, int port, String str) {
		JSONObject jo = JSONObject.fromObject(str);
		Integer pageId = (Integer) jo.get("pageId");
		JSONArray ja = (JSONArray) jo.get("data");
		@SuppressWarnings("unchecked")
		Collection<JSONObject> cmnts = ((JSONObject) jo.get("cmnts")).values();
		System.out.println(str);
		Connection conn = new DBConnection().getConnection();
		try {
			for (int i = 0; i < ja.size(); i++) {
				JSONObject j = (JSONObject) ja.get(i);
				String sql = "insert into marker(idPage,txt,tp,v,ip,port) values(?,?,?,?,?,?)";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setInt(1, pageId);
				ps.setString(2, j.getString("txt"));
				ps.setString(3, j.getString("tp"));
				ps.setString(4, j.getString("v"));
				ps.setString(5, ip);
				ps.setInt(6, port);
				ps.executeUpdate();
			}
			for (JSONObject j : cmnts) {
				if (j.getInt("status") == 2) {
					String sql = "update markit.comment set cmnt = ? where id = ? and idPage = ?";
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.setString(1, j.getString("cmnt"));
					ps.setInt(2, j.getInt("id"));
					ps.setInt(3, pageId);
					ps.executeUpdate();
				} else {
					String sql = "insert into comment(idPage,id,cmnt,usr,time) values(?,?,?,?,?)";
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.setInt(1, pageId);
					ps.setInt(2, j.getInt("id"));
					ps.setString(3, j.getString("cmnt"));
					ps.setString(4, ip);
					ps.setString(5, j.getString("time"));
					ps.executeUpdate();
				}
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
